package cpu.footprint.ui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import cpu.footprint.R;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.ResultMessage;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.util.CreateDialogUtil;
import cpu.footprint.util.FileUtil;

import static cpu.footprint.api.ApiUrl.URL_FILEPATH;
import static cpu.footprint.util.FileUtil.copyFile;
import static cpu.footprint.util.FileUtil.getImageContentUri;

/**
 * Created by Administrator on 2017/3/11.
 */
@ContentView(R.layout.activity_personinfo)
public class PersonInfoActivity extends BaseActivity {
    @ViewInject(R.id.activity_personinfo)
    private LinearLayout activity_personinfo;
    @ViewInject(R.id.image_head)
    private RoundedImageView image_head;//头像
    @ViewInject(R.id.edit_realName)
    private EditText edit_realName;//真实姓名
    @ViewInject(R.id.edit_nickName)
    private EditText edit_nickName;//昵称
    @ViewInject(R.id.edit_birthday)
    private EditText edit_birthday;//生日
    @ViewInject(R.id.edit_individualSignature)
    private EditText edit_individualSignature;//个性签名
    @ViewInject(R.id.edit_address)
    private EditText edit_address;//地址
    @ViewInject(R.id.edit_email)
    private EditText edit_email;//邮箱
    @ViewInject(R.id.text_phoneNumber)
    private TextView text_phoneNumber;//电话
    @ViewInject(R.id.radio_man)
    private RadioButton radio_man;//男
    @ViewInject(R.id.radio_woman)
    private RadioButton radio_woman;//女
    @ViewInject(R.id.title_content)
    private TextView title_content;//标题栏内容
    @ViewInject(R.id.title_menu_text)
    private TextView title_menu_text;//标题栏功能
    @ViewInject(R.id.title_menu_image)
    private ImageView title_menu_image;//标题栏功能
    @ViewInject(R.id.radio_group_sex)
    private RadioGroup radio_group_sex;
    private User user = new User();
    private static final int REQUEST_CODE_PICK_IMAGE = 3;
    private static final int CROP_BIG_PICTURE = 13;
    private static final int TAKE_BIG_PICTURE = 14;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 7;
    private String HeadPicture;// 头像base64
    private String mModilePhone;//电话号码
    private String mToken;//Token
    private boolean IsEditoring = false;
    //此App一些信息的存储文件夹路径
    private Uri imageUri = Uri.parse(ApiUrl.URL_FILEPATH + "head.jpg");
    private boolean IsUpdateInfo = false;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (mDialog != null) {
                if (mDialog.isShowing())
                    mDialog.dismiss();
            }
            switch (msg.what) {
                case ResultMessage.UPDATE_INFO_SUCCESS:
                    CreateDialogUtil.ToastShow(mContext, "更新资料成功！");
                    IsUpdateInfo = true;
                    break;
                case ResultMessage.UPDATE_INFO_FAILED:
                    IsUpdateInfo = false;
                    CreateDialogUtil.ToastShow(mContext, msg.obj.toString());
                    break;
                case ResultMessage.GET_HEAD_SUCCESS:
                    byte[] binaryData = (byte[]) msg.obj;
                    if (binaryData.length != 0) {
                        Bitmap head = BitmapFactory.decodeByteArray(binaryData, 0, binaryData.length);
                        image_head.setImageBitmap(head);
                        head.recycle();
                    } else {

                    }
                    break;
                case ResultMessage.GET_HEAD_FAILED:
                    CreateDialogUtil.ToastShow(mContext, msg.obj.toString());
                    break;
                case ResultMessage.UPDATE_HEAD_SUCCESS:
                    CreateDialogUtil.ToastShow(mContext, "更换头像成功！");
                    IsUpdateInfo = true;
                    break;
                case ResultMessage.UPDATE_HEAD_FAILED:
                    CreateDialogUtil.ToastShow(mContext, msg.obj.toString());
                    IsUpdateInfo = false;
                    break;
                case ResultMessage.FAILED:
                    CreateDialogUtil.ToastShow(mContext, "连接失败");
                    break;
                case ResultMessage.TIMEOUT:
                    CreateDialogUtil.ToastShow(mContext, "连接超时");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = myApplication.getUser();
        initView();
    }

    /**
     * 初始化布局
     */
    private void initView() {
        title_menu_image.setVisibility(View.GONE);
        mModilePhone = user.getMobilePhone();
        mToken = user.getToken();
        title_content.setText("个人信息");
        title_menu_text.setText("编辑");
        mDialog = showLoadingDialog(this);
        initViewUnClickable();
        initData();

    }

    private void initData() {
        if (user != null) {
            if (user.getNickName() != null && !user.getNickName().equals("null"))
                edit_nickName.setText("" + user.getNickName());
            if (user.getIndividualSignature() != null && !user.getIndividualSignature().equals("null"))
                edit_individualSignature.setText("" + user.getIndividualSignature());
            if (user.getAddress() != null && !user.getAddress().equals("null"))
                edit_address.setText("" + user.getAddress());
            if (user.getBirthday() != null && !user.getBirthday().equals("null"))
                edit_birthday.setText("" + user.getBirthday());
            if (user.getEmail() != null && !user.getEmail().equals("null"))
                edit_email.setText("" + user.getEmail());
            if (user.getMobilePhone() != null && !user.getMobilePhone().equals("null"))
                text_phoneNumber.setText("" + user.getMobilePhone());
            if(user.getRealName()!=null&&!user.getRealName().isEmpty())
                edit_realName.setText("" + user.getRealName());
            updateImage();
            int count = activity_personinfo.getChildCount();
            for (int i = 0; i < count; i++) {
                View view = activity_personinfo.getChildAt(i);
                if (view instanceof EditText) { // EditText
                    EditText edit = (EditText) view;
                    int length = edit.getText().toString().length();
                    edit.setSelection(length);
                }
            }
        }
    }

    @Event(value = {R.id.title_back, R.id.image_head, R.id.title_menu_text})
    private void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back: {
                if (IsUpdateInfo)
                    setResult(11);
                else
                    setResult(12);
                finish();
                overridePendingTransition(0,R.anim.fade);
            }
            break;
            case R.id.image_head: {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                //    指定下拉列表的显示数据
                final String[] cities = {"拍照", "相册"};
                //    设置一个下拉的列表选择项
                builder.setItems(cities, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0: {
                                takePhone();
                            }
                            break;
                            case 1: {
                                choosePhone();
                            }
                            break;
                        }
                    }
                });
                builder.show();
            }
            break;
            case R.id.title_menu_text: {
                if (!IsEditoring) {
                    IsEditoring = true;
                    title_menu_text.setText("完成");
                    initViewClickable();
                } else {
                    title_menu_text.setText("修改");
                    initViewUnClickable();
                    changeInfo();
                }
            }
            break;
        }
    }

    /**
     * 获取编辑的个人信息
     */
    private void changeInfo() {
        String NickName = edit_nickName.getText().toString().trim();
        String RealName = edit_realName.getText().toString().trim();
        String Address = edit_address.getText().toString().trim();
        String Birthday = edit_birthday.getText().toString().trim();
        String Email = edit_email.getText().toString().trim();
        String IndividualSignature = edit_individualSignature.getText().toString().trim();
        String Sex = "男";
        if (radio_man.isChecked())
            Sex = "男";
        else
            Sex = "女";
        Map<String, String> map = new HashMap<>();
        map.put("mobilePhone", mModilePhone);
        map.put("token", mToken);
        map.put("realName", RealName);
        map.put("nickName", NickName);
        map.put("birthday", Birthday);
        map.put("sex", Sex);
        map.put("address", Address);
        map.put("email", Email);
        map.put("individualSignature", IndividualSignature);
        updateInfo(map);
    }

    private void updateInfo(Map<String, String> map) {
        mDialog.show();
        APIService.Post(ApiUrl.URL_UPDATE_USERINFO, map, new RespCallBack<BaseBean<User>>(this) {
            @Override
            public void onSuccess(BaseBean<User> result) {
                super.onSuccess(result);
                Toast(result.info);
                if (result.success) {
                    myApplication.setUser(result.data);
                    user = result.data;
                    initData();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mDialog.dismiss();
            }
        });
    }

    /**
     * 实现控件可用
     */
    void initViewClickable() {
        radio_group_sex.setEnabled(true);
        edit_nickName.setEnabled(true);
        edit_birthday.setEnabled(true);
        edit_address.setEnabled(true);
        edit_email.setEnabled(true);
        edit_individualSignature.setEnabled(true);
        edit_realName.setEnabled(true);
        radio_man.setClickable(true);
        radio_woman.setClickable(true);
    }

    /**
     * 实现控件不可用
     */
    void initViewUnClickable() {
        radio_group_sex.setEnabled(false);
        edit_nickName.setEnabled(false);
        text_phoneNumber.setEnabled(false);
        edit_email.setEnabled(false);
        edit_birthday.setEnabled(false);
        edit_address.setEnabled(false);
        edit_individualSignature.setEnabled(false);
        edit_realName.setEnabled(false);
        radio_man.setClickable(false);
        radio_woman.setClickable(false);
    }

    /**
     * 更新头像
     *
     * @param
     */
    private void updateImage() {
        String fileName = URL_FILEPATH + user.getMobilePhone() + ".png";
        if (FileUtil.fileIsExists(fileName)) {
            Uri uri = Uri.fromFile(new File(fileName));
            image_head.setImageURI(uri);
        } else if (user.getHeadPicture() != null && !user.getHeadPicture().equals("")) {
            String imgUrl = ApiUrl.URL_HOST + user.getHeadPicture();
            Picasso.with(PersonInfoActivity.this).load(imgUrl).placeholder(R.mipmap.defaultpicture).into(image_head);
        }
    }

    /**
     * Activity回调函数
     *
     * @param req
     * @param res
     * @param data
     */
    public void onActivityResult(int req, int res, Intent data) {
        switch (req) {
            /**
             * 从相册中选取图片的请求标志
             */
            case REQUEST_CODE_PICK_IMAGE:
                if (res == Activity.RESULT_OK) {
                    try {
                        /**
                         * 该uri是上一个Activity返回的
                         */
                        imageUri = data.getData();
//                        String filePath=getRealPathFromUri(mContext,imageUri);
                        //File file1=new File(filePath);
                        File file1 = FileUtil.uri2File(imageUri, PersonInfoActivity.this);
                        File file2 = new File(ApiUrl.URL_FILEPATH + "head_new.png");
                        copyFile(file1, file2);
                        imageUri = Uri.parse(ApiUrl.URL_FILEPATH + "head.png");
                        imageUri = getImageContentUri(PersonInfoActivity.this, file2);
                        cropImageUri(imageUri, 400, 400, CROP_BIG_PICTURE);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(this, "选择图片失败！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.i("liang", "失败");
                }
                break;
            case CROP_BIG_PICTURE://截取图片
                if (imageUri != null) {
                    Bitmap bitmap = decodeUriAsBitmap(imageUri);
                    if (bitmap == null) {
                        return;
                    }
                    image_head.setImageBitmap(bitmap);
                    bitmap = FileUtil.imageZoom(bitmap);
                    FileUtil.saveMyBitmap(URL_FILEPATH + user.getMobilePhone() + ".png", bitmap);
                    updateImage();
                    updateHeadPic();
                }
                break;
            case TAKE_BIG_PICTURE://照相
                cropImageUri(imageUri, 400, 400, CROP_BIG_PICTURE);
                break;
            default:
                break;
        }
    }

    private void updateHeadPic() {
        mDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("mobilePhone", mModilePhone);
        map.put("token", mToken);
        map.put("type", 1);
        map.put("file", new File(URL_FILEPATH + user.getMobilePhone() + ".png"));
        APIService.upLoadFile(ApiUrl.URL_UPDATE_HEADPIC, map, new RespCallBack<BaseBean<String>>(this) {
            @Override
            public void onSuccess(BaseBean<String> result) {
                super.onSuccess(result);
                Toast(result.info);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mDialog.dismiss();
            }
        });
    }


    public void choosePhone() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE2);

        } else {
            choosePhoto();
        }
    }

    /**
     * 拍照
     */
    void takePhoto() {
        File file = new File(Environment.getExternalStorageDirectory(), "footprint");
        if (!file.exists()) {
            file.mkdir();
        }
        File output = new File(file, "head.png");
        try {
            if (output.exists()) {
                output.delete();
            }
            output.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 隐式打开拍照的Activity，并且传入CROP_PHOTO常量作为拍照结束后回调的标志
         */
        imageUri = Uri.fromFile(output);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_BIG_PICTURE);//or TAKE_SMALL_PICTURE
        overridePendingTransition(0,R.anim.fade);
    }

    /**
     * 从相册选取图片
     */
    void choosePhoto() {
        /**
         * 打开选择图片的界面
         */
        File chooseImage = new File(ApiUrl.URL_FILEPATH, "head.png");
        if (chooseImage.exists())
            chooseImage.delete();
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE); //
        overridePendingTransition(0,R.anim.fade);
    }

    /**
     * 剪切图片
     *
     * @param uri
     * @param outputX
     * @param outputY
     * @param requestCode
     */
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
        overridePendingTransition(0,R.anim.fade);
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePhoto();
            } else {
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                choosePhoto();
            } else {
                // Permission Denied
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 检查权限
     */
    public void takePhone() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE2);
        } else {
            takePhoto();
        }
    }

    /**
     * 重写后退事件
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int count = event.getRepeatCount();// 排除长按事件，或者快速点击事件干扰
        Log.e("event repeatCount", "" + count);
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (IsUpdateInfo)
                setResult(11);
            else
                setResult(12);
            finish();
            overridePendingTransition(0,R.anim.fade);
            return true;// 返回true,表示当前事件事件不再被传递，false继续传递
        }
        return false;
    }
}
